package com.bmps.springcloud.insuredmicroservice.service.rabbitmq.production;


import com.bmps.springcloud.insuredmicroservice.model.rabbitmq.RabbitPolicyModel;
import com.bmps.springcloud.insuredmicroservice.service.accept.InsuranceAcceptService;
import com.bmps.springcloud.insuredmicroservice.util.amqp.DateUtils;
import com.bmps.springcloud.insuredmicroservice.util.amqp.JsonUtils;
import com.bmps.springcloud.insuredmicroservice.util.mail.MailUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author: lazasha
 * @date: 2019/12/24  13:28
 **/
@Service
public class AcceptReturnCallback implements RabbitTemplate.ReturnCallback {
    private final Logger logger = LoggerFactory.getLogger(AcceptConfirmCallback.class);
    private final InsuranceAcceptService insuranceAcceptService;
    private final MailUtil mailUtil;

    public AcceptReturnCallback(InsuranceAcceptService insuranceAcceptService, MailUtil mailUtil) {
        this.insuranceAcceptService = insuranceAcceptService;
        this.mailUtil = mailUtil;
    }

    @Override
    public void returnedMessage(Message message, int i, String s, String s1, String s2) {
       
        String jsonStr = new String(message.getBody());
        RabbitPolicyModel rabbitPolicyModel = JsonUtils.JSON2Object(jsonStr,RabbitPolicyModel.class);
        logger.error("保单号：" + rabbitPolicyModel.getContno()
                +"消息发送失败,未发送到指定队列:\n"
                + "返回时间: " + DateUtils.localDateTimeToString(LocalDateTime.now())
                + ",Message: " + jsonStr
                + ",replyCode: " + i
                + ",replyText: " + s  //错误原因
                + ",exchange: " + s1
                + ",routingKey: " + s2);//queue名称
        //可以更新数据库标志位推送mq不成功，让批处理来处理为发送成功的消息
        //发送邮件通知消息发送不成功，已经转为批处理
//        mailUtil.sendMail("消息生产者发送消息失败","【保单号】：" + rabbitPolicyModel.getContno()
//                +"【消息发送失败,未发送到指定队列】:\n"
//                + "【返回时间】: " + DateUtils.localDateTimeToString(LocalDateTime.now())
//                + ",【消息体】: " + jsonStr
//                + ",【错误原因】: " + s
//                + ",【交换机】: " + s1);
        try {
            insuranceAcceptService.updateAcceptPushFlag(0, rabbitPolicyModel.getContno(), 4);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("系统异常，异常信息为：" + e.getMessage());
        }

    }
}
